<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

use Goutte\Client;
use GuzzleHttp\Client as GuzzleClient;
use App\Models\Article;

class FetchArticleChinese extends Command
{
    const DOWNLOAD_URL_PREFIX = 'http://www.zoores.ac.cn/CN/abstract/abstract%u.shtml';
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fetch:cn_article {id?} {--start=} ';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $id = $this->argument('id');
        $startId = $this->option('start');

        if ($id) {
            $this->getCNInfo(Article::where('zr_id', $id)->first());
        } else {
            $page = 1;
            $count = 0;
            while (true) {
                if ($startId) {
                    $articles = Article::where('id', '>=', $startId)->simplePaginate(5, ['*'], 'page', $page);
                } else {
                    $articles = Article::simplePaginate(5, ['*'], 'page', $page);
                }
                
                $break = (bool)(count($articles->items()) == 0);
                foreach ($articles as $article) {
                    $this->getCNInfo($article);
                    $count++;
                }

                if ($break) break;
                $page++;
                $this->info($count++ . 'th articles pdf fetched.');
            }
        }
    }

    private function getCNInfo($article)
    {
        $id = $article->zr_id;

        try {
            $client = new Client();
            $guzzleClient = new GuzzleClient(array(
                'timeout' => 60,
            ));
            $client->setClient($guzzleClient);

            $this->info('ZR ID: ' . $id . ',  ' . $article->id . ' start');
            $url = sprintf(self::DOWNLOAD_URL_PREFIX, $id);
            $crawler = $client->request('GET', $url);

            $title = $crawler->filterXpath('//span[@class="J_biaoti"]');
            if ($title->count() > 0) {
                $title = $title->html();
            } else {
                return null;
            }
            $authorList = $crawler->filterXpath('//td[@class="J_author_cn"]');
            if ($authorList->count() > 0) {
                $authorList = $authorList->html();
            } else {
                $authorList = '';
            }
            $aff = $crawler->filterXpath('//span[@class="J_author_dizhi"]');
            if ($aff->count() > 0) {
                $aff = $aff->html();
            } else {
                $aff = '';
            }
            $abstract = $crawler->filterXpath('//span[@class="J_zhaiyao"]');
            if ($abstract->count() > 0) {
                $abstract = $abstract->html();
            } else {
                $abstract = '';
            }
            $keywords = $crawler->filterXpath('//td[@class="J_zhaiyao"]//a[@class="txt_zhaiyao1"]');

            $keywordsArr = [];
            if ($keywords->count() > 0) {
                $keywords->each(function($item, $i) use (&$keywordsArr) {
                    $keywordsArr[] = $item->text();
                });
            }
            $iArr = array(
                'cn_title' => $title,
                'cn_author_list' => $authorList,
                'cn_affiliation' => $aff,
                'cn_abstract' => $abstract, 
                'cn_keywords' => implode('; ', $keywordsArr)
            );

            Article::where('id', $article->id)
                ->update($iArr);

            $this->info('ZR ID: ' . $id . ',  ' . $article->id . ' done');
        } catch(\Exception $e) {
            echo $e->getMessage(); exit;
        }
    }
}
